package cn.virens.library.uitls;

import android.content.Context;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 文件工具类
 *
 * @author :loioi
 * @package :cn.loioi.util
 * @创建时间 :2016/3/26 9:59
 */
public class FileHelper {
    /**
     * 获取data/files 目录，优先获取SD卡下的data目录
     *
     * @param context
     * @return
     */
    public static File getDataFilesDir(Context context) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
            return context.getExternalFilesDir(null);
        } else {
            return context.getFilesDir();
        }
    }

    /**
     * 获取data/files目录下的文件
     *
     * @param context
     * @param fileName
     * @return
     */
    public static File getDataFile(Context context, String fileName) {
        return new File(getDataFilesDir(context), fileName);
    }

    /**
     * 拷贝assets下的文件到data/files目录下
     *
     * @param context
     * @param formFile
     * @param toFile
     * @return
     */
    public static boolean copyAssetsDirToDataDir(Context context, String formFile, String toFile) {
        InputStream input = null;
        OutputStream output = null;
        try {
            File to = FileHelper.getDataFile(context, toFile);
            if (!to.exists()) {
                to.createNewFile();
            }
            input = context.getAssets().open(formFile);
            output = new FileOutputStream(to);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
        } catch (IOException e) {
            return false;
        } finally {
            try {
                if (input != null) input.close();
                if (output != null) output.close();
            } catch (Exception e) {
            }
        }
        return true;
    }
}
